package com.fujimana.rockincat.restree.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.fujimana.rockincat.restree.bytecode.ClassFile;

public class FileInputClassLoader extends ClassLoader {

	private static final int BUF_SIZE = 1024;

	public FileInputClassLoader() {
		super(Thread.currentThread().getContextClassLoader());
	}

	public Class<?> loadClassFile(File classFile) throws IOException,
			ClassNotFoundException {
		FileInputStream in = new FileInputStream(classFile);
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		byte[] buf = new byte[BUF_SIZE];
		int len = in.read(buf);

		while (len != -1) {
			out.write(buf, 0, len);
			len = in.read(buf);
		}

		byte[] loadedData = out.toByteArray();

		ClassFile cf = new ClassFile(new DataInputStream(
				new ByteArrayInputStream(loadedData)));

		String clazz = cf.getClassName();

		return Class.forName(clazz);
	}

	public Class<?> loadClassFile(String name) throws IOException,
			ClassNotFoundException {
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(name);
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		byte[] buf = new byte[BUF_SIZE];
		int len = in.read(buf);

		while (len != -1) {
			out.write(buf, 0, len);
			len = in.read(buf);
		}

		byte[] loadedData = out.toByteArray();

		ClassFile cf = new ClassFile(new DataInputStream(
				new ByteArrayInputStream(loadedData)));

		String clazz = cf.getClassName();

		return Class.forName(clazz);
	}
}